package com.example.clone;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.edroid.apkhooker.R;
import com.example.clone.Client.Callback;
import com.example.utils.Zmlib;

public class CloneActivity extends ActionBarActivity implements OnCheckedChangeListener,
		OnClickListener, OnItemClickListener, android.os.Handler.Callback {
	public static final int PORT = 8889;
	private static Map<String, String> map;
	private ListView lv1;

	private TextView tv_info;
	private ToggleButton tgbt;
	private Server server;
	private Client client;

	private List<Data> data;
	private MyAdapter adapter;
	private Handler handler;
	
	private static class Data {
		String name, path;
		boolean isChecked;
	}

	/**
	 * key=显示名<br/>
	 * value=路径
	 * 
	 * @param map
	 */
	public static void setData(Map<String, String> map) {
		CloneActivity.map = map;
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_clone);

		String ipv4 = Zmlib.getLocalIpAddress();
		if (ipv4 == null) {
			Zmlib.msgBoxOk(this, "未连接网络",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
		} else {
			server = new Server(this);
			client = new Client(this);
			handler = new Handler(this);
			
			findViewById(R.id.bt1).setOnClickListener(this);
			findViewById(R.id.bt2).setOnClickListener(this);
			findViewById(R.id.bt3).setOnClickListener(this);
			findViewById(R.id.bt4).setOnClickListener(this);

			tv_info = (TextView) findViewById(R.id.tv1);
			tv_info.setText("本机: " + ipv4 + ":" + PORT);

			tgbt = (ToggleButton) findViewById(R.id.toggleButton1);
			tgbt.setOnCheckedChangeListener(this);

			lv1 = (ListView) findViewById(R.id.lv1);
			if (map != null) {
				data = new ArrayList<Data>();
				for (Map.Entry<String, String> entry : map.entrySet()) {
					Data item = new Data();
					item.name = entry.getKey();
					item.path = entry.getValue();
					data.add(item);
				}
				adapter = new MyAdapter();
				lv1.setAdapter(adapter);
//				lv1.setOnItemClickListener(this);
			}
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (server != null)
			server.stopServer();
		map = null;
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch(buttonView.getId()) {
		case R.id.toggleButton1:
			if (isChecked) {
				server.startServer();
			} else {
				server.stopServer();
			}
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt1:// 全选
			for (Data item : data) {
				item.isChecked = true;
			}
			adapter.notifyDataSetChanged();
			break;
		case R.id.bt2:// 反选
			for (Data item : data) {
				item.isChecked = !item.isChecked;
			}
			adapter.notifyDataSetChanged();
			break;
		case R.id.bt3:// 取消
			for (Data item : data) {
				item.isChecked = false;
			}
			adapter.notifyDataSetChanged();
			break;
		case R.id.bt4:// 克隆
			startClone();
			break;
		case R.id.chk1:
			Data item = (Data) v.getTag();
			item.isChecked = ((CheckBox)v).isChecked();
			break;
		default:
			break;
		}
	}

	private class MyAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = getLayoutInflater().inflate(
						R.layout.listitem_clone, parent, false);
			}
			CheckBox chk = (CheckBox) convertView.findViewById(R.id.chk1);
			TextView tv = (TextView) convertView.findViewById(R.id.tv1);
			Data item = data.get(position);
			chk.setChecked(item.isChecked);
			chk.setOnClickListener(CloneActivity.this);//不能使用onCheckedChange，因为只要状态改变就会响应，造成勾选状态无法保存
			chk.setTag(item);
			tv.setText(item.name);
			return convertView;
		}

	}

	private void log(Object o) {
		Log.e(this.getClass().getSimpleName(), "" + o);
	}
	private CloneActivity getThis() {
		return this;
	}
	private void startClone() {
		client.searchServer(new Callback() {
			@Override
			public void callback(boolean result) {
				if (result) {//找到服务器
					for(Data item : data) {
						if(item.isChecked) {
							if (TextUtils.isEmpty(item.path)) {
								update();//路径为空，更新apk
							} else {
								final Data info = item;
								client.download(item.path, item.path, new Callback() {
									@Override
									public void callback(boolean result) {
										String str ="下载:"+info.name+" >>> "+(result?"成功":"失败");
//										Zmlib.toast(getThis(),str);
										handler.obtainMessage(1, str).sendToTarget();
									}
								});
							}
						}
					}
				} else {
					Zmlib.msgBoxOk(CloneActivity.this, "未找到服务器", null);
				}
			}
		});
	}

	private void update() {
		final String filename = Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/update.apk";
		client.download("", filename, new Callback() {
			@Override
			public void callback(boolean result) {
				if (result) {
					Zmlib.installApk(CloneActivity.this, new File(filename));
				} else {
//					Zmlib.toastLong(CloneActivity.this, "下载失败");
					handler.obtainMessage(1, "下载失败").sendToTarget();
				}
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Data item = data.get(position);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case 1:
			Zmlib.msgBoxOk(this, msg.obj.toString(), null);
			break;

		default:
			break;
		}
		return false;
	}

}
